package com.ln.prac.base.m202206.d17;

import java.io.*;

/**
 * <pre>
 *  单例 - 懒汉式 -线程安全 - 内部类
 * </pre>
 *
 * @Author zhangj
 * @Date 2022/6/17 23:46
 */
public class SingletonWithInner implements Serializable {


    private SingletonWithInner() {
    }

    private static class SingletonWithInnerHolder {
        private static final SingletonWithInner INS = new SingletonWithInner();
    }

    public static SingletonWithInner getInstance() {
        return SingletonWithInnerHolder.INS;
    }

    /**
     * 当进行反序列化的时候，会自动调用该方法，将该方法的返回值直接返回
     */
    public Object readResolve() {
        return SingletonWithInnerHolder.INS;
    }

    public static void main(String[] args) throws IOException, ClassNotFoundException {
        for (int i = 0; i < 10; i++) {
            new Thread(() -> {
                System.out.println(getInstance());
            }).start();
        }

        // 测试 解决 破解单例 - 序列化的方式
        writeObjectFromFIle();
        readObjectFromFIle();


    }

    public static void readObjectFromFIle() throws IOException, ClassNotFoundException {
        // 创建对象输入流对象
        ObjectInputStream ois = new ObjectInputStream(new FileInputStream("a.txt"));
        // 读取对象
        SingletonWithInner singleton = (SingletonWithInner) ois.readObject();

        System.out.println(singleton);
        // 释放资源
        ois.close();
    }

    public static void writeObjectFromFIle() throws IOException {
        // 读取对象
        SingletonWithInner singleton = getInstance();
        // 创建对象输入流对象
        ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("a.txt"));
        // 写对象
        oos.writeObject(singleton);
        // 关闭
        oos.close();
    }



}
